package com.cn.customer.housekeeping.housekeepingc.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.cn.customer.housekeeping.housekeepingc.R;
import com.cn.customer.housekeeping.housekeepingc.bean.BaseResp;
import com.cn.customer.housekeeping.housekeepingc.biz.personcenter.IUserLoginView;
import com.cn.customer.housekeeping.housekeepingc.biz.personcenter.InterfacePresenter;
import com.cn.customer.housekeeping.housekeepingc.bridge.BridgeFactory;
import com.cn.customer.housekeeping.housekeepingc.bridge.Bridges;
import com.cn.customer.housekeeping.housekeepingc.bridge.cache.sharePref.EBSharedPrefManager;
import com.cn.customer.housekeeping.housekeepingc.bridge.cache.sharePref.EBSharedPrefUser;
import com.cn.customer.housekeeping.housekeepingc.ui.base.BaseActivity;
import com.cn.customer.housekeeping.housekeepingc.ui.base.QuickAdapter;
import com.cn.customer.housekeeping.housekeepingc.ui.helper.ItemHelper;
import com.cn.customer.housekeeping.housekeepingc.util.ToastUtil;
import com.lfq.pulltorefresh.library.PullToRefreshBase;
import com.lfq.pulltorefresh.library.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;


/***
 *地图选择位置
 */
public class MapChoiceActivity extends BaseActivity implements IUserLoginView, PoiSearch.OnPoiSearchListener {


    private InterfacePresenter mInterfacePresenter;
    private ListView mListView;
    private PullToRefreshListView mPullToRefreshListView;
    private int pageNum = 1;
    private int pageSize = 20;
    private TextView tvwu;
    private AMap aMap;
    private MapView mapView;
    private ImageView ivRelease;
    private EBSharedPrefManager manager = BridgeFactory.getBridge(Bridges.SHARED_PREFERENCE);
    private PoiResult poiResult; // poi返回的结果
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;
    private List<PoiItem> poiItems;// poi数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.listview_headview_mapchoice);
        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        ivRelease = (ImageView) findViewById(R.id.iv_release);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initViews() {
        mInterfacePresenter = new InterfacePresenter();
        mInterfacePresenter.attachView(this);
        if (aMap == null) {
            aMap = mapView.getMap();

        }
        setUpMap();
        mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
        mPullToRefreshListView.setMode(PullToRefreshBase.Mode.DISABLED);
        mListView = mPullToRefreshListView.getRefreshableView();
        mListView.setHeaderDividersEnabled(false);
        mListView.setDividerHeight(0);
    }

    @Override
    public void initListeners() {
        ivRelease.setOnClickListener(this);
        mPullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageNum = 1;

//                mInterfacePresenter.getBlacklist(pageNum, pageSize);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//                mInterfacePresenter.getBlacklist(pageNum, pageSize);
            }
        });

        mPullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int headerCount = mListView.getHeaderViewsCount();
                if (position >= headerCount) {
                    PoiItem item = mAdapter.getItem(position - headerCount);
                    Intent mIntent = new Intent();
                    mIntent.putExtra("PoiItem",item);
                    setResult(Activity.RESULT_OK, mIntent);
                    finish();
                }
            }
        });
    }

    private QuickAdapter<PoiItem> mAdapter;

    @Override
    public void initData() {
        ItemHelper mItemHelper = new ItemHelper();
        mAdapter = mItemHelper.setAdapteMapChoice(MapChoiceActivity.this, new ArrayList());
        mListView.setAdapter(mAdapter);


    }

    private void setUpMap() {
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                LatLng latLng1 = new LatLng(Double.valueOf(manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.lat, "")), Double.valueOf(manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.lon, "")));
                aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                        latLng1, 13, 0, 0)));
                addMarkerCenterPoint();
            }
        });

        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition position) {
            }

            @Override
            public void onCameraChangeFinish(CameraPosition postion) {
                LatLonPoint latLonPoint = new LatLonPoint(postion.target.latitude, postion.target.longitude);
//                getAddress(latLonPoint);
                doSearchQuery(latLonPoint);
            }
        });


    }


    /**
     * 开始进行poi搜索
     */
    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(LatLonPoint latLonPoint) {
        String keyWord = "楼栋号";
        currentPage = 0;
        query = new PoiSearch.Query(keyWord, "楼栋号", manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.city, ""));// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(currentPage);// 设置查第一页

        if (latLonPoint != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);
            poiSearch.setBound(new PoiSearch.SearchBound(latLonPoint, 5000, true));//
            // 设置搜索区域为以lp点为圆心，其周围5000米范围
            poiSearch.searchPOIAsyn();// 异步搜索
        }
    }


    /**
     * 在地图添加中心点位置
     */
    private void addMarkerCenterPoint() {
        LatLng latLng = aMap.getCameraPosition().target;
        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
        Marker screenMarker = aMap.addMarker(new MarkerOptions().position(latLng)
//                .anchor(0.0f,0.0f)
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_hong)));
        screenMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
    }

    @Override
    public void setHeader() {
        super.setHeader();
        rlTitle.setVisibility(View.VISIBLE);
        ivTopBack.setVisibility(View.VISIBLE);
        tvTopTitle.setText("选择位置");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_release:
                LatLng latLng1 = new LatLng(Double.valueOf(manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.lat, "")), Double.valueOf(manager.getKDPreferenceUserInfo().getString(EBSharedPrefUser.lon, "")));
                aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                        latLng1, 13, 0, 0)));
                break;
        }

        super.onClick(v);
    }

    @Override
    public void onError(BaseResp s) {
        mPullToRefreshListView.onRefreshComplete();
    }

    @Override
    public void onSuccess(BaseResp s) {
        mPullToRefreshListView.onRefreshComplete();

    }

    @Override
    public void showLoading() {
        super.showLoading();
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
    }


    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }


    @Override
    public void onPoiSearched(PoiResult result, int rcode) {
        if (rcode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                    if (poiItems != null && poiItems.size() > 0) {


                        mAdapter.replaceAll(poiItems);


                    } else {
                        ToastUtil.makeText(MapChoiceActivity.this,
                                "没有查询到相关信息");
                    }
                }
            } else {
                ToastUtil.makeText(MapChoiceActivity.this,
                        "没有查询到相关信息");
            }
        } else {
            ToastUtil.makeText(MapChoiceActivity.this,
                    rcode + "");
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {
    }
}
